﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace A3ServiceLibrary
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together.
    public class AuthenticationService : IAuthenticationService
    {
        private static readonly List<IAuthenticationCallback> _subscribers = new List<IAuthenticationCallback>();

        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }

        public void Authenticate(String username, String password)
        {
            _subscribers.ForEach(delegate(IAuthenticationCallback callback)
            {
                if (((ICommunicationObject)callback).State == CommunicationState.Opened)
                {
                    callback.OnAuthentication(username, password);
                }
                else
                {
                    _subscribers.Remove(callback);
                }
            });

        }

        public bool Subscribe()
        {
            try
            {
                IAuthenticationCallback callback = OperationContext.Current.GetCallbackChannel<IAuthenticationCallback>();
                if (!_subscribers.Contains(callback))
                    _subscribers.Add(callback);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool Unsubscribe()
        {
            try
            {
                IAuthenticationCallback callback = OperationContext.Current.GetCallbackChannel<IAuthenticationCallback>();
                if (_subscribers.Contains(callback))
                    _subscribers.Remove(callback);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
